﻿using System;
using System.IO;
using System.Web;
using up7.db.model;
using up7.db.utils;

namespace up7.db.biz
{
    /// <summary>
    /// 路径生成器基类
    /// 提供文件或文件夹的存储路径
    /// </summary>
    public class PathBuilder
    {
        /// <summary>
        /// 根级存储路径,格式：up7\\upload
        /// </summary>
        /// <returns></returns>
        public string getRoot()
        {
            ConfigReader cr = new ConfigReader();
            var uploadFolder = cr.io_dir;
            uploadFolder = uploadFolder.Replace("{root}", HttpContext.Current.Server.MapPath("/"));

            return uploadFolder;
        }

        public virtual string genFolder(string uid,string nameLoc)
        {
            return string.Empty;
        }

        public virtual string genFolder(string uid, ref FolderInf fd)
        {
            return string.Empty;
        }

        /// <summary>
        /// 生成文件夹存储路径
        /// upload/2023/03/01/guid/文件夹名称
        /// </summary>
        /// <param name="fd"></param>
        /// <returns></returns>
        public virtual string genFolder(FileInf fd)
        {
            var uuid = fd.id; //取消生成新ID,使用原始文件夹ID
            DateTime timeCur = DateTime.Now;
            string path = Path.Combine(this.getRoot(), timeCur.ToString("yyyy"));
            path = Path.Combine(path, timeCur.ToString("MM"));
            path = Path.Combine(path, timeCur.ToString("dd"));
            path = Path.Combine(path, uuid);
            path = Path.Combine(path, fd.nameLoc);

            return path;
        }

        public virtual string genFile(string uid, ref FileInf f)
        {
            return string.Empty;
        }
        public virtual string genFile(string uid, string md5, string nameLoc)
        {
            return string.Empty;
        }

        /// <summary>
        /// 相对路径转换成绝对路径
        /// /2021/05/28/guid/nameLoc => d:/upload/2021/05/28/guid/nameLoc
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public string relToAbs(string path)
        {
            string root = this.getRoot();
            root = root.Replace("\\", "/");
            path = path.Replace("\\", "/");
            //没有路径前缀->添加路径前缀
            if (!path.StartsWith(root))
            {
                path = PathTool.combin(root, path);
            }
            return path;
        }

        /// <summary>
        /// 将路径转换成相对路径
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public string absToRel(string path)
        {
            string root = this.getRoot().Replace("\\", "/");
            path = path.Replace("\\", "/");
            path = path.Replace(root, string.Empty);
            return path.Trim();
        }
    }
}